package com.lq.file.filemanager.server.client;

import com.lq.file.filemanager.entity.FtpFileServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.SocketException;

/**
 * @program: file-manager
 * @description:
 * @author: LQ
 * @create: 2021-08-07 13:06
 */

@Slf4j
@Component
public class MyFtpClient {
    @Autowired
    private FtpFileServer fileServer;

    public FTPClient ftpClient() {
        FTPClient ftpClient = new FTPClient();
        //设置连接超时时间
        ftpClient.setConnectTimeout(fileServer.getFileServerConnectTimeOut());
        //设置ftp字符集
        ftpClient.setControlEncoding(fileServer.getFileServerControlEncoding());
        //设置被动模式，文件传输端口设置
        // ftpClient.enterLocalPassiveMode();
        try {
            //设置文件传输模式为二进制，可以保证传输的内容不会被改变
            // ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            // ftpClient.connect(beansEntity.getIp()+":"+beansEntity.getPort());
            ftpClient.setDefaultPort(fileServer.getFileServerPort());
            ftpClient.connect(fileServer.getFileServerHost(), fileServer.getFileServerPort());
            ftpClient.login(fileServer.getUsername(), fileServer.getPassword());
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                ftpClient.disconnect();
                log.info("未连接到FTP，用户名或密码错误!");
                return null;
            } else {
                log.info("FTP连接成功!");
                return ftpClient;
            }
        } catch (SocketException socketException) {
            log.error("FTP的IP地址可能错误，请正确配置!");
            return null;
        } catch (IOException ioException) {
            ioException.printStackTrace();
            log.error("FTP的端口错误,请正确配置!");
            return null;
        }

    }
}
